package dept_controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	dd "pear-admin-layui-go/app/sys/dept/domain"
	ds "pear-admin-layui-go/app/sys/dept/service"
	"pear-admin-layui-go/framework/login_filter"
	fr "pear-admin-layui-go/framework/result"
	ft "pear-admin-layui-go/framework/table"
	"strconv"
	"time"
)

func Tree(c *gin.Context) {
	depts := ds.Tree()
	tree := ToTree(depts, 0)
	c.JSON(http.StatusOK, map[string]any{
		"status": map[string]any{
			"code":    200,
			"message": "操作成功",
		},
		"data": tree,
	})
}

func ToTree(depts []dd.Dept, pid int64) []map[string]any {
	var tree = make([]map[string]any, 0)
	for i := 0; i < len(depts); i++ {
		v := depts[i]
		if v.Pid == pid {
			children := ToTree(depts, v.Id)
			last := true
			if len(children) > 0 {
				last = false
			}
			tree = append(tree, map[string]any{
				"id":       v.Id,
				"title":    v.Name,
				"parentId": pid,
				"children": children,
				"last":     last,
			})
		}
	}
	return tree
}

func Edit(c *gin.Context) {
	var der dd.DeptEditRequest
	_ = c.ShouldBind(&der)
	user, _ := login_filter.GetCurrentUser(c)
	der.UpdateTime = time.Now().Unix()
	der.UpdateBy = user.Id
	der.UpdateName = user.Username
	db := ds.Edit(&der)
	fr.Result(c, db)
}

func EditPage(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	dept := ds.EditPage(id)
	c.HTML(http.StatusOK, "sys/dept/edit.html", gin.H{
		"id":       id,
		"name":     dept.Name,
		"location": dept.Location,
		"remark":   dept.Remark,
	})
}

func Save(c *gin.Context) {
	var dsr dd.DeptSaveRequest
	_ = c.ShouldBind(&dsr)
	user, _ := login_filter.GetCurrentUser(c)
	dsr.CreateTime = time.Now().Unix()
	dsr.CreateBy = user.Id
	dsr.CreateName = user.Username
	_, db := ds.Save(&dsr)
	fr.Result(c, db)
}

func AddPage(c *gin.Context) {
	pid := c.DefaultQuery("pid", "0")
	c.HTML(http.StatusOK, "sys/dept/add.html", gin.H{
		"pid": pid,
	})
}

func Table(c *gin.Context) {
	var dtr dd.DeptTableRequest
	_ = c.ShouldBind(&dtr)
	table, count := ds.Table(&dtr)
	var dtrs = make([]dd.DeptTableResponse, len(table))
	for i, v := range table {
		dtrs[i] = dd.DeptTableResponse{
			Id:         v.Id,
			Name:       v.Name,
			Leader:     v.Leader,
			LeaderName: v.LeaderName,
			Pid:        v.Pid,
			Location:   v.Location,
			Number:     v.Number,
			Remark:     v.Remark,
			CreateTime: v.CreateTime,
			CreateName: v.CreateName,
			UpdateTime: v.UpdateTime,
			UpdateName: v.UpdateName,
		}
	}
	c.JSON(http.StatusOK, ft.TableResponse{
		Data:  dtrs,
		Count: count,
	})
}

func Dept(c *gin.Context) {
	c.HTML(http.StatusOK, "sys/dept/dept.html", gin.H{})
}
